<?php

require_once dirname(__FILE__) . '/discuz_post.class.php';

#通过 archiver 获取论坛的板块列表

function getHttpDiscuzForumBanKuaiListFromArchiver($url = 'http://www.xp121.com/archiver/', $boolhost = true) {
    $s = snoopy_fetch($url, $boolhost);
    $pLink = '#<li><a href="\?fid\-([\d]+)\.html">(.*)</a></li>#isU';
    preg_match_all($pLink, $s, $d);
    if (empty($d[1])) {
        $pLink = '#<li><a href="fid-([\d]+)\.html">(.*)</a></li>#';
        preg_match_all($pLink, $s, $d);
    }
    $arrResult = array();
    if (!$d[1] || !is_array($d[1]) || empty($d[1])) {
        return false;
    }
    foreach ($d[1] as $k => $intForumId) {
        $arrResult[$intForumId] = $d[2][$k];
    }
    return $arrResult;
}

#通过论坛的XML接口获取板块列表

function getHttpDiscuzForumBanKuaiListFromLoginXML($url, $boolhost = true) {
    $ext = 'forum.php?mod=misc&action=nav&infloat=yes&handlekey=nav&referer=http%3A%2F%2Fwww.xp121.com%2Fforum.php%3Fmod%3Dguide%26view%3Dmy&inajax=1&ajaxtarget=fwin_content_nav';
    $url = $url . $ext;
    $s = snoopy_fetch($url, $boolhost);
    $ppForum = '#<ul id="fs_group">(.*)</ul>#isU';
    preg_match_all($ppForum, $s, $d);
    $ppForumLink = '#<li fid="([\d]+)">(.*)</li>#isU';
    preg_match_all($ppForumLink, $d[0][0], $e);
    $arrResult = array();
    foreach ($e[1] as $k => $v) {
        $arrResult[$k]['fid'] = $v;
        $arrResult[$k]['fname'] = $e[2][$k];
        $pParent = '#<ul id="fs_forum_' . $v . '">(.*)</ul>#isU';
        preg_match_all($pParent, $s, $f);
        preg_match_all($ppForumLink, $f[1][0], $g);
        $arrResult[$k]['list'] = array();
        foreach ($g[1] as $kk => $vv) {
            $arrResult[$k]['list'][$kk]['fid'] = $vv;
            $arrResult[$k]['list'][$kk]['fname'] = $g[2][$kk];
        }
    }
    print_r($arrResult);
    return $arrResult;
}

function getVarExportArrConfigDiscuzForum($url, $boolhost = true) {
    $e = getHttpDiscuzForumBanKuaiListFromLoginXML($url, $boolhost);
    $result = array();
    if (is_array($e) && $e) {
        foreach ($e as $k => $v) {
            foreach ($v['list'] as $vv) {
                $result[$v['fname']][$vv['fname']] = array($vv['fname']);
            }
        }
    }
    return $result;
}

#通过本地名称获取服务器的fid

function getServerForumId($pForum, $newcate, $boolhost = true) {
    static $serverForum;
    $url = 'http://' . FORUM_DOMAIN . '/';
    if (!$serverForum) {
        $serverForum = getHttpDiscuzForumBanKuaiListFromLoginXML($url, $boolhost);
        foreach ($serverForum as &$v) {
            $v['fname'] = preg_replace('#\s+#isU', '', $v['fname']);
            foreach ($v['list'] as &$vv) {
                $vv['fname'] = preg_replace('#\s+#isU', '', $vv['fname']);
            }unset($vv);
        }unset($v);
    }
    foreach ($serverForum as $v) {
        if (strtolower($v['fname']) == strtolower(preg_replace('#\s+#isU', '', $pForum))) {
            foreach ($v['list'] as $vv) {
                if (strtolower($vv['fname']) == strtolower(preg_replace('#\s+#isU', '', $newcate))) {
                    return $vv['fid'];
                }
            }
        }
    }
    return 0;
}

/*
  activationauth		104
  formhash	432e795e	106
  J7soat	china@888	105
  k9Grj2	china@888	105
  n4445v	think889966@sina.com	116
  referer	http://www.xp121.com/./	120
  regsubmit	yes	145
  w66jKK	think889966	107
 */

function registerDiscuzUserByHttp() {
    clearFormHashFile();
    clearLocalCookie();

    $strUrlRegister = 'http://' . FORUM_DOMAIN . '/member.php?mod=register&inajax=1';

    $strRegisterPage = 'http://' . FORUM_DOMAIN . '/member.php?mod=register';

    $snoopy = new Snoopy;
    $snoopy->agent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; QQDownload 716; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.30729; .NET4.0C)";
    $snoopy->referer = 'http://' . FORUM_DOMAIN . '/forum.php';
    $snoopy->rawheaders["Pragma"] = "no-cache";
    $snoopy->host = FORUM_DOMAIN;
    $snoopy1 = $snoopy2 = clone $snoopy;
    #访问注册页面
    $snoopy->fetch($strRegisterPage);
    #设置注册页面的Cookie
    setLocalCookie($snoopy->headers);
    #注册页面的内容,解析FormHash和Kv
    $s = $snoopy->results;

    $strUserName = getOneRandUserName();
    $strUserEmail = getOneRandUserEmail();
    $data = array();
    $password = 'China@12345';

    $pRfm = '#<div class="rfm">(.*)</div>#isU';
    preg_match_all($pRfm, $s, $Rfm);
    if (count($Rfm[1]) != 4) {
        logformat('ERROR:Parse rfm Div Failed! Div Count:' . count($Rfm[1]));
        logformat('ERROR:Please Check The Page Structure! Url:' . $strRegisterPage);
        return false;
    }

    $pPassword = '#<td><input type="password" id="([^\s]+)"#isU';
    preg_match_all($pPassword, $Rfm[1][1], $d);
    $data[$d[1][0]] = $password;

    $pEmail = '#<td><input type="text" id="([^\s]+)"#';
    preg_match_all($pEmail, $Rfm[1][3], $e);
    $data[$e[1][0]] = $strUserEmail;

    $pUsername = '#<td><input type="text" id="([^\s]+)"#isU';
    preg_match_all($pUsername, $Rfm[1][0], $u);
    $data[$u[1][0]] = $strUserName;

    $pRepeatPw = '#<td><input type="password" id="([^\s]+)"#isU';
    preg_match_all($pRepeatPw, $Rfm[1][2], $rp);
    $data[$rp[1][0]] = $password;

    $pFormHash = '#<input type="hidden" name="formhash" value="(.*)" />#isU';
    preg_match_all($pFormHash, $s, $fh);
    $data['formhash'] = $fh[1][0];

    $data['regsubmit'] = 'yes';
    $data['referer'] = 'http://' . FORUM_DOMAIN . '/member.php?mod=register';
    $data['activationauth'] = '';

    $snoopy1->referer = 'http://' . FORUM_DOMAIN . '/member.php?mod=register';
    $snoopy1->rawheaders["COOKIE"] = getLocalCookie();

    $snoopy1->submit($strUrlRegister, $data);
    $result = $snoopy1->results;
    if (strpos($result, '感谢您注册') || strpos($result, '感谢您的注册')) {
        //获取UID
        $pUid = "#,'uid':'([\d]+)'\}\);\}#isU";
        preg_match_all($pUid, $result, $arrUserInfo);
        logformat('NOTICE:Http Register Success...Uid:' . $arrUserInfo[1][0]);
        if (!$arrUserInfo[1][0] || !is_numeric($arrUserInfo[1][0])) {
            logformat('ERROR:Http Register Success...But Get Uid Failed:' . $arrUserInfo[1][0]);
            die();
        }
        file_put_contents(APP_USER_EMAIL_HAS_REGISTER_FILE, $strUserName . PHP_EOL, 8);
        file_put_contents(APP_USER_EMAIL_HAS_REGISTER_FILE, $strUserEmail . PHP_EOL, 8);
        $GLOBALS['varStore']['hasRegisterUser'][] = $strUserName;
        $GLOBALS['varStore']['hasRegisterUser'][] = $strUserEmail;

        $arrResult = array('username' => $strUserName, 'email' => $strUserEmail, 'password' => $password, 'uid' => $arrUserInfo[1][0]);

        $strUserPassUid = json_encode($arrResult);
        file_put_contents(APP_USER_PASS_UID_REGISTER_FILE, $strUserPassUid . PHP_EOL, 8);
        $GLOBALS['varStore']['UserPassUid'][] = $arrResult;
        return $arrResult;
    }
    echo $s;
    logformat('ERROR:Http Register Failed!' . print_r($data, true));
    return false;
}

#随机注册一个用户到Disduz

function registerDiscuzUserByDbInsert($db_prefix) {
    $intMaxUid = getMaxUserIdFromDiscuzDb($db_prefix);
    $startUserId = $intMaxUid + 1;

    $salt = md5(mt_rand(0, 10000000));
    $salt = substr($salt, mt_rand(0, 20), 6);
    $password = md5(md5('China@123456789') . $salt);
    $regTime = mt_rand(1254605752, time());

    $strUserName = getOneRandUserName();
    $strUserEmail = getOneRandUserEmail();

    $query1 = "INSERT INTO `{$db_prefix}ucenter_members` SET  uid='{$startUserId}',secques='', username='{$strUserName}', password='{$password}', email='" . $strUserEmail . "', regip='" . mt_rand(1, 255) . '.' . mt_rand(1, 255) . '.' . mt_rand(1, 255) . '.' . mt_rand(1, 255) . "', regdate='" . $regTime . "', salt='{$salt}';" . PHP_EOL;
    to_db_query($query1);

    $query2 = "INSERT INTO  `{$db_prefix}ucenter_memberfields` SET uid='{$startUserId}';" . PHP_EOL;
    to_db_query($query2);

    $query3 = "INSERT INTO `{$db_prefix}common_member` VALUES ({$startUserId},'" . $strUserEmail . "','{$strUserName}','{$password}',0,0,0,0,0,10,0,'',{$regTime},2,0,'9999',0,1,0,0,0,0);" . PHP_EOL;
    to_db_query($query3);
}

#获取当前最大的uid

function getMaxUserIdFromDiscuzDb($db_prefix) {
    $query = "SELECT MAX(uid) as uid FROM `{$db_prefix}ucenter_memberfields`";
    $result = db_select($query);
    return intval($result[0]['uid']);
}

#获取一个可以发帖的用户

function getDiscuzRandPubUser() {
    $count = count($GLOBALS['varStore']['UserPassUid']);
    $key = mt_rand(0, $count - 1);
    return $GLOBALS['varStore']['UserPassUid'][$key];
}

#快速批量创建分区和板块
//$arrInsertCategory[$v['cid1']][$v['cid2']][] = $v['cid3'];

function Tools_discuz_discuz_makeForumList($arrInsertCategory, $arrSeoKeyWords = array(), $prefix = 'lk_', $t = false) {

    $returnDataArray = array();

    $arrForumKeywords = $arrSeoKeyWords;
    $strForumFile = APP_DATA_PATH . 'forumlist.sql';
    @unlink($strForumFile);
    $startId = 101;
    foreach ($arrInsertCategory as $arrInsert) {
        foreach ($arrInsert as $strFenqu => $arrBankuai) {
            $forumId = $startId;
            $keywords = '';
            $title = '';
            $index = 0;
            $tindex = 0;
            if ($t) {
                shuffle($arrSeoKeyWords);
            }
            foreach ($arrSeoKeyWords as $strKw) {
                if (!is_array($strKw)) {
                    $keywords.=$strFenqu . $strKw . ',';
                    if ($index < 3) {
                        $title.=$strFenqu . $strKw . '-';
                    }
                    $index++;
                } else {
                    //如果是数组
                    foreach ($strKw as $GuanJianZi => $arrFenquBanKuai) {
                        if (in_array($strFenqu, $arrFenquBanKuai)) {
                            $keywords.=$strFenqu . $GuanJianZi . ',';
                            if ($index < 2) {
                                $title.=$strFenqu . $GuanJianZi . '-';
                            }
                            $tindex++;
                        }
                    }
                }
            }
            $keywords = substr($keywords, 0, -1);
            $desc = $keywords;

            $query = "INSERT INTO `" . $prefix . "forum_forum` VALUES ({$forumId},0,'group','{$strFenqu}',1,0,0,0,0,0,'','',0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,4,4,0,1,0,0,1,0,0,0,0,0,0,0,0);" . PHP_EOL;
            file_put_contents($strForumFile, $query, 8);

            $query = "INSERT INTO `" . $prefix . "forum_forumfield` VALUES ({$forumId},'','','','','','','','','','','','','','','','','','','{$title}{bbname}','{$keywords}','{$desc}','','','','',0,0,0,0,0,0,0,'','',0,'','',0,0);" . PHP_EOL;
            file_put_contents($strForumFile, $query, 8);

            $fupId = $forumId;
            $startId++;

            if (is_array($arrBankuai)) {
                foreach ($arrBankuai as $strBankuai) {
                    $forumId = $startId;
                    $returnDataArray[$strFenqu . '|' . $strBankuai] = $forumId;
                    $keywords = '';
                    $title = '';
                    $index = 0;
                    $tindex = 0;
                    if ($t) {
                        shuffle($arrForumKeywords);
                    }
                    foreach ($arrForumKeywords as $strKw) {
                        if (!is_array($strKw)) {
                            $keywords.=$strBankuai . $strKw . ',';
                            if ($index < 3) {
                                if (!$fgroup) {
                                    $title.=$strBankuai . $strKw . '-';
                                } else {
                                    $title.=$strBankuai . '{fgroup}' . $strKw . '-';
                                }
                            }
                            $index++;
                        } else {
                            foreach ($strKw as $GuanJianZi => $arrFenquBanKuai) {
                                if (in_array($strBankuai, $arrFenquBanKuai) || in_array($strFenqu, $arrFenquBanKuai)) {
                                    $keywords.=$strBankuai . $GuanJianZi . ',';
                                    if ($tindex < 2) {
                                        $title.=$strBankuai . $GuanJianZi . '-';
                                    }
                                    $tindex++;
                                }
                            }
                        }
                    }
                    $keywords = substr($keywords, 0, -1);
                    $desc = $keywords;

                    $query = "INSERT INTO `" . $prefix . "forum_forum` VALUES ({$forumId},{$fupId},'forum','{$strBankuai}',1,0,0,0,0,0,'','',1,0,1,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0);" . PHP_EOL;
                    file_put_contents($strForumFile, $query, 8);

                    $query = "INSERT INTO `" . $prefix . "forum_forumfield` VALUES ({$forumId},'','','','','','','','','','','','','','','','','','','{$title}{bbname}','{$keywords}','{$desc}','','','','',0,0,0,0,0,0,0,'','',0,'','',0,0);" . PHP_EOL;
                    file_put_contents($strForumFile, $query, 8);
                    $startId++;
                }
            }
        }
    }
    return $returnDataArray;
}

?>